#include "mathlink.h"

#include <math.h>
#include <stdlib.h>
#include <stdio.h>


extern void LinkList( double * coord, long coordLen, double threshold);

void LinkList( double * coord, long coordLen, double threshold)
{
	int coord_num;
	coord_num = coordLen / 3;

	int * pIdx;// = (double *) malloc(coord_num * (coord_num + 1) / 2 * sizeof (double));
	double dx, dy, dz, dist;

	int i, j, count;
	
	count = 0;
	for(i = 0; i < coord_num; i++)
	{
		for(j = 0; j < i; j++)
		{
			dx = coord[3*i+0] - coord[3*j+0];
			dy = coord[3*i+1] - coord[3*j+1];
			dz = coord[3*i+2] - coord[3*j+2];
			dist = sqrt(dx*dx + dy*dy + dz*dz);
			if (dist < threshold)
				count ++;	
		}
	}
	
	pIdx = (int *) malloc ( 2 * count * sizeof (int) );

	count = 0;
	for(i = 0; i < coord_num; i++)
	{
		for(j = 0; j < i; j++)
		{
			dx = coord[3*i+0] - coord[3*j+0];
			dy = coord[3*i+1] - coord[3*j+1];
			dz = coord[3*i+2] - coord[3*j+2];
			dist = sqrt(dx*dx + dy*dy + dz*dz);
			if (dist < threshold)
			{
				pIdx[2*count + 0 ] = i + 1;
				pIdx[2*count + 1 ] = j + 1;
				count ++;
			}	
		}
	}


	MLPutInteger32List(stdlink, pIdx, 2 * count);
	
	return;	
}



int main(int argc, char* argv[])
{
	return MLMain(argc, argv);
}

